package com.wideplay.warp.clustering.swarmcache;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.wideplay.warp.clustering.DataGridService;
import com.wideplay.warp.clustering.GridScoped;
import net.sf.swarmcache.CacheConfiguration;
import net.sf.swarmcache.CacheFactory;

import java.lang.annotation.Annotation;

/**
 * Created with IntelliJ IDEA.
 * On: 23/06/2007
 *
 * @author Dhanji R. Prasanna
 * @since 1.0
 */
class SwarmDataGridService extends DataGridService {
    private final Injector injector;

    @Inject
    public SwarmDataGridService(Injector injector, SpacesListWrapper wrapper) {
        super(wrapper.getSpaceNames());

        this.injector = injector;
    }

    public synchronized void start() {
        if (spaceNames.isEmpty()) {
            createSpace(GridScoped.class, injector.getInstance(CacheConfiguration.class));
        } else {
            //register all caches as necessary (configs should be bound at appropriate annotation keys)
            for (Class<? extends Annotation> spaceName : super.spaceNames) {
                createSpace(spaceName, injector.getInstance(Key.get(CacheConfiguration.class, spaceName)));
            }
        }
    }

    private void createSpace(Class<? extends Annotation> spaceName, CacheConfiguration configuration) {
        final SwarmDataGridImpl dataGrid = new SwarmDataGridImpl();
        dataGrid.setCache(new CacheFactory(configuration).createCache(spaceName.getName()));

        register(spaceName, dataGrid);
    }

}
